package com.hmall.order.interceptor;

import com.hmall.order.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class AuthorizationInterceptor implements HandlerInterceptor {

    public static ThreadLocal<String> local = new ThreadLocal();

    /**
     * 预处理
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authorization = request.getHeader("authorization");
        if (StringUtils.isBlank(authorization)) {
            log.warn("用户非法访问, 请求路径: {}", request.getRequestURI());
            // 未登录，403
            response.setStatus(403);
            return false;
        }
        Long userId = Long.valueOf(authorization);
        UserHolder.setUser(userId);
        log.info("set userId => {}", userId);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清除用户信息
        UserHolder.removeUser();
        log.info("清除用户信息");
    }
}
